package com.yalemang.framework.base

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import androidx.viewbinding.ViewBinding
import com.yalemang.framework.utils.ViewBindingUtils

/**
 * todo D 不能使用List<*>
 * 否则ViewBinding工具类报错
 */
abstract class BaseVBAdapter<D, VB : ViewBinding>(
    var dataList: ArrayList<D> // 数据源
) : RecyclerView.Adapter<BaseVBAdapter.CommonViewHolder<VB>>() {

    // Item点击事件
    lateinit var itemClickListener: (data: D, position: Int) -> Unit
    // Item长点击事件
    lateinit var itemLongClickListener: (data: D, position: Int) -> Boolean

    /**
     * 动态添加数据
     */
    open fun addData(loadMoreDataList : MutableList<D>) {
        dataList.addAll(loadMoreDataList)
        notifyDataSetChanged()
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CommonViewHolder<VB> {
        val vb = getItemViewBinding(LayoutInflater.from(parent.context))
        return if (vb != null) {
            CommonViewHolder(vb)
        } else {
            CommonViewHolder(ViewBindingUtils.getViewBinding(this, parent.context))
        }
    }

    open fun getItemViewBinding(layoutInflater: LayoutInflater):VB? {
        return null
    }

    override fun onBindViewHolder(holder: CommonViewHolder<VB>, position: Int) {
        // 点击事件
        holder.itemView.setOnClickListener {
            if (this::itemClickListener.isInitialized) {
                itemClickListener.invoke(dataList[position], position)
            }
        }

        // 长点击时间
        holder.itemView.setOnLongClickListener {
            if (this::itemLongClickListener.isInitialized) {
                itemLongClickListener.invoke(dataList[position], position)
            } else {
                // 默认不消费事件，长按松开可触发点击时间
                false
            }
        }

        // 刷新UI数据等
        val data = dataList[position]
        onBindViewHolder(holder, data, position)
    }

    protected abstract fun onBindViewHolder(holder: CommonViewHolder<VB>, data: D, position: Int)

    override fun getItemCount(): Int {
        return dataList.size
    }

    class CommonViewHolder<VB : ViewBinding>(var binding: VB) : RecyclerView.ViewHolder(binding.root)

}